package com.zyf.wjy.controller;

import com.zyf.wjy.common.Result;
import com.zyf.wjy.entity.Field;
import com.zyf.wjy.service.FieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地块管理控制器
 */
@Controller
@RequestMapping("/field")
public class FieldController {
    
    @Autowired
    private FieldService fieldService;
    
    /**
     * 地块列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Field> fields = fieldService.findAll();
        model.addAttribute("fields", fields);
        return "field/list";
    }
    
    /**
     * 新增/编辑页面
     */
    @GetMapping("/edit")
    public String edit(@RequestParam(required = false) Long id, Model model) {
        if (id != null) {
            Field field = fieldService.findById(id);
            model.addAttribute("field", field);
        }
        return "field/edit";
    }
    
    /**
     * 保存地块
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<Field> save(@RequestBody Field field) {
        try {
            Field saved = fieldService.save(field);
            return Result.success("保存成功", saved);
        } catch (Exception e) {
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除地块
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        try {
            boolean success = fieldService.deleteById(id);
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有地块（用于下拉选择）
     */
    @GetMapping("/all")
    @ResponseBody
    public Result<List<Field>> getAll() {
        List<Field> fields = fieldService.findAll();
        return Result.success(fields);
    }
    
    /**
     * 获取地块详情
     */
    @GetMapping("/detail/{id}")
    @ResponseBody
    public Result<Field> detail(@PathVariable Long id) {
        Field field = fieldService.findById(id);
        if (field != null) {
            return Result.success(field);
        } else {
            return Result.error("地块不存在");
        }
    }
}

